class SolarSystem {
    constructor() {
        this.canvas = document.getElementById('solarSystem');
        this.ctx = this.canvas.getContext('2d');
        this.animationId = null;
        this.isPaused = false;
        this.speedMultiplier = 1;
        this.time = 0;
        
        // 画布中心点
        this.centerX = 0;
        this.centerY = 0;
        
        // 初始化画布大小
        this.resizeCanvas();
        
        // 行星数据（包括冥王星）
        this.planets = [
            {
                name: '水星',
                radius: 4,
                distance: 80,
                speed: 0.04,
                color: '#8C7853',
                angle: 0
            },
            {
                name: '金星',
                radius: 6,
                distance: 110,
                speed: 0.035,
                color: '#FFC649',
                angle: 0
            },
            {
                name: '地球',
                radius: 7,
                distance: 150,
                speed: 0.03,
                color: '#6B93D6',
                angle: 0,
                satellites: [
                    {
                        name: '月球',
                        radius: 2,
                        distance: 20,
                        speed: 0.15,
                        color: '#C0C0C0',
                        angle: 0
                    }
                ]
            },
            {
                name: '火星',
                radius: 5,
                distance: 190,
                speed: 0.025,
                color: '#C1440E',
                angle: 0
            },
            {
                name: '木星',
                radius: 20,
                distance: 280,
                speed: 0.015,
                color: '#D8CA9D',
                angle: 0
            },
            {
                name: '土星',
                radius: 18,
                distance: 350,
                speed: 0.012,
                color: '#FAD5A5',
                angle: 0,
                hasRings: true
            },
            {
                name: '天王星',
                radius: 12,
                distance: 420,
                speed: 0.008,
                color: '#4FD0E7',
                angle: 0
            },
            {
                name: '海王星',
                radius: 11,
                distance: 480,
                speed: 0.006,
                color: '#4B70DD',
                angle: 0
            },
            {
                name: '冥王星',
                radius: 3,
                distance: 540,
                speed: 0.004,
                color: '#9CA6B7',
                angle: 0
            }
        ];
        
        this.initEventListeners();
        this.start();
    }
    
    resizeCanvas() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight - 100; // 减去控制面板高度
        this.centerX = this.canvas.width / 2;
        this.centerY = this.canvas.height / 2;
    }
    
    initEventListeners() {
        // 窗口大小改变
        window.addEventListener('resize', () => {
            this.resizeCanvas();
        });
        
        // 速度控制
        const speedSlider = document.getElementById('speed');
        const speedValue = document.getElementById('speedValue');
        speedSlider.addEventListener('input', (e) => {
            this.speedMultiplier = parseFloat(e.target.value);
            speedValue.textContent = this.speedMultiplier.toFixed(1) + 'x';
        });
        
        // 暂停/继续按钮
        const pauseBtn = document.getElementById('pauseBtn');
        pauseBtn.addEventListener('click', () => {
            if (this.isPaused) {
                this.start();
                pauseBtn.textContent = '暂停';
            } else {
                this.pause();
                pauseBtn.textContent = '继续';
            }
        });
        
        // 重置按钮
        const resetBtn = document.getElementById('resetBtn');
        resetBtn.addEventListener('click', () => {
            this.reset();
        });
    }
    
    drawSun() {
        const ctx = this.ctx;
        
        // 太阳光晕效果
        const gradient = ctx.createRadialGradient(
            this.centerX, this.centerY, 0,
            this.centerX, this.centerY, 40
        );
        gradient.addColorStop(0, '#FFD700');
        gradient.addColorStop(0.3, '#FFA500');
        gradient.addColorStop(0.6, '#FF8C00');
        gradient.addColorStop(1, 'rgba(255, 140, 0, 0)');
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(this.centerX, this.centerY, 40, 0, Math.PI * 2);
        ctx.fill();
        
        // 太阳核心
        ctx.fillStyle = '#FFD700';
        ctx.beginPath();
        ctx.arc(this.centerX, this.centerY, 15, 0, Math.PI * 2);
        ctx.fill();
        
        // 太阳闪烁效果
        const flicker = Math.sin(this.time * 0.1) * 0.1 + 0.9;
        ctx.globalAlpha = flicker;
        ctx.fillStyle = '#FFFF00';
        ctx.beginPath();
        ctx.arc(this.centerX, this.centerY, 12, 0, Math.PI * 2);
        ctx.fill();
        ctx.globalAlpha = 1;
        
        // 太阳标签
        ctx.fillStyle = '#FFD700';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('太阳', this.centerX, this.centerY - 25);
    }
    
    drawOrbit(distance) {
        // 轨道效果已被移除
        // const ctx = this.ctx;
        // ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        // ctx.lineWidth = 1;
        // ctx.beginPath();
        // ctx.arc(this.centerX, this.centerY, distance, 0, Math.PI * 2);
        // ctx.stroke();
    }
    
    drawSatelliteOrbit(centerX, centerY, distance) {
        // 卫星轨道效果已被移除
        // const ctx = this.ctx;
        // ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)';
        // ctx.lineWidth = 1;
        // ctx.beginPath();
        // ctx.arc(centerX, centerY, distance, 0, Math.PI * 2);
        // ctx.stroke();
    }
    
    drawSatellite(satellite, planetX, planetY) {
        const ctx = this.ctx;
        
        // 计算卫星位置（相对于行星）
        const satX = planetX + Math.cos(satellite.angle) * satellite.distance;
        const satY = planetY + Math.sin(satellite.angle) * satellite.distance;
        
        // 绘制卫星轨道 - 已移除
        // this.drawSatelliteOrbit(planetX, planetY, satellite.distance);
        
        // 绘制卫星
        const gradient = ctx.createRadialGradient(
            satX - satellite.radius * 0.3, satY - satellite.radius * 0.3, 0,
            satX, satY, satellite.radius
        );
        gradient.addColorStop(0, this.lightenColor(satellite.color, 0.4));
        gradient.addColorStop(1, satellite.color);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(satX, satY, satellite.radius, 0, Math.PI * 2);
        ctx.fill();
        
        // 卫星边缘高光
        ctx.strokeStyle = this.lightenColor(satellite.color, 0.6);
        ctx.lineWidth = 0.5;
        ctx.beginPath();
        ctx.arc(satX, satY, satellite.radius, 0, Math.PI * 2);
        ctx.stroke();
        
        // 绘制卫星标签
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        const labelY = satY + satellite.radius + 12;
        ctx.fillText(satellite.name, satX, labelY);
        
        // 绘制卫星运行轨迹 - 已移除
        // this.drawSatelliteTrail(satellite, satX, satY);
    }
    
    drawTrail(planet, currentX, currentY) {
        // 行星轨迹效果已被移除
        // const ctx = this.ctx;
        // const trailLength = 20;
        
        // if (!planet.trail) {
        //     planet.trail = [];
        // }
        
        // planet.trail.push({ x: currentX, y: currentY });
        
        // if (planet.trail.length > trailLength) {
        //     planet.trail.shift();
        // }
        
        // for (let i = 0; i < planet.trail.length - 1; i++) {
        //     const alpha = i / planet.trail.length * 0.3;
        //     ctx.strokeStyle = `rgba(255, 255, 255, ${alpha})`;
        //     ctx.lineWidth = 1;
        //     ctx.beginPath();
        //     ctx.moveTo(planet.trail[i].x, planet.trail[i].y);
        //     ctx.lineTo(planet.trail[i + 1].x, planet.trail[i + 1].y);
        //     ctx.stroke();
        // }
    }
    
    drawSatelliteTrail(satellite, currentX, currentY) {
        // 卫星轨迹效果已被移除
        // const ctx = this.ctx;
        // const trailLength = 15;
        
        // if (!satellite.trail) {
        //     satellite.trail = [];
        // }
        
        // satellite.trail.push({ x: currentX, y: currentY });
        
        // if (satellite.trail.length > trailLength) {
        //     satellite.trail.shift();
        // }
        
        // for (let i = 0; i < satellite.trail.length - 1; i++) {
        //     const alpha = i / satellite.trail.length * 0.2;
        //     ctx.strokeStyle = `rgba(192, 192, 192, ${alpha})`;
        //     ctx.lineWidth = 0.5;
        //     ctx.beginPath();
        //     ctx.moveTo(satellite.trail[i].x, satellite.trail[i].y);
        //     ctx.lineTo(satellite.trail[i + 1].x, satellite.trail[i + 1].y);
        //     ctx.stroke();
        // }
    }
    
    drawPlanet(planet) {
        const ctx = this.ctx;
        
        // 计算行星位置
        const x = this.centerX + Math.cos(planet.angle) * planet.distance;
        const y = this.centerY + Math.sin(planet.angle) * planet.distance;
        
        // 绘制轨道 - 已移除
        // this.drawOrbit(planet.distance);
        
        // 绘制土星环
        if (planet.hasRings) {
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.ellipse(x, y, planet.radius + 8, planet.radius + 3, 0, 0, Math.PI * 2);
            ctx.stroke();
        }
        
        // 绘制行星
        const gradient = ctx.createRadialGradient(
            x - planet.radius * 0.3, y - planet.radius * 0.3, 0,
            x, y, planet.radius
        );
        gradient.addColorStop(0, this.lightenColor(planet.color, 0.3));
        gradient.addColorStop(1, planet.color);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(x, y, planet.radius, 0, Math.PI * 2);
        ctx.fill();
        
        // 行星边缘高光
        ctx.strokeStyle = this.lightenColor(planet.color, 0.5);
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(x, y, planet.radius, 0, Math.PI * 2);
        ctx.stroke();
        
        // 绘制行星标签
        ctx.fillStyle = 'white';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        const labelY = y + planet.radius + 15;
        ctx.fillText(planet.name, x, labelY);
        
        // 绘制运行轨迹（淡淡的尾迹效果）- 已移除
        // this.drawTrail(planet, x, y);
        
        // 绘制卫星
        if (planet.satellites) {
            planet.satellites.forEach(satellite => {
                this.drawSatellite(satellite, x, y);
            });
        }
    }
    
    lightenColor(color, factor) {
        // 简单的颜色变亮函数
        const hex = color.replace('#', '');
        const r = parseInt(hex.substr(0, 2), 16);
        const g = parseInt(hex.substr(2, 2), 16);
        const b = parseInt(hex.substr(4, 2), 16);
        
        const newR = Math.min(255, Math.floor(r + (255 - r) * factor));
        const newG = Math.min(255, Math.floor(g + (255 - g) * factor));
        const newB = Math.min(255, Math.floor(b + (255 - b) * factor));
        
        return `rgb(${newR}, ${newG}, ${newB})`;
    }
    
    drawStars() {
        const ctx = this.ctx;
        
        // 生成随机星星
        if (!this.stars) {
            this.stars = [];
            for (let i = 0; i < 200; i++) {
                this.stars.push({
                    x: Math.random() * this.canvas.width,
                    y: Math.random() * this.canvas.height,
                    size: Math.random() * 2 + 0.5, // 稍微增大星星尺寸
                    brightness: Math.random() * 0.8 + 0.2, // 基础亮度
                    twinkleSpeed: Math.random() * 0.02 + 0.005, // 闪烁速度
                    twinklePhase: Math.random() * Math.PI * 2, // 闪烁相位
                    twinkleType: Math.random() < 0.3 ? 'fast' : (Math.random() < 0.5 ? 'slow' : 'normal'), // 闪烁类型
                    color: Math.random() < 0.1 ? (Math.random() < 0.5 ? '#FFE4B5' : '#E6E6FA') : '#FFFFFF' // 少数星星有颜色
                });
            }
        }
        
        // 绘制星星
        this.stars.forEach(star => {
            let twinkle = 1;
            
            // 根据闪烁类型计算不同的闪烁效果
            switch(star.twinkleType) {
                case 'fast':
                    // 快速闪烁
                    twinkle = Math.sin(this.time * star.twinkleSpeed * 3 + star.twinklePhase) * 0.4 + 0.6;
                    // 添加随机闪烁突变
                    if (Math.random() < 0.002) {
                        twinkle *= Math.random() * 0.5 + 0.5;
                    }
                    break;
                case 'slow':
                    // 缓慢闪烁
                    twinkle = Math.sin(this.time * star.twinkleSpeed * 0.5 + star.twinklePhase) * 0.3 + 0.7;
                    // 添加呼吸效果
                    twinkle *= (Math.sin(this.time * star.twinkleSpeed * 0.2) * 0.2 + 0.8);
                    break;
                default:
                    // 正常闪烁
                    twinkle = Math.sin(this.time * star.twinkleSpeed + star.twinklePhase) * 0.35 + 0.65;
                    // 添加二次谐波增加复杂性
                    twinkle *= (Math.sin(this.time * star.twinkleSpeed * 2 + star.twinklePhase) * 0.15 + 0.85);
            }
            
            // 随机闪烁强化效果
            if (Math.random() < 0.001) {
                twinkle *= Math.random() * 0.3 + 1.2; // 偶尔特别亮
            }
            
            // 计算最终亮度
            const finalBrightness = star.brightness * twinkle;
            
            // 绘制星星光晕（对于较亮的星星）
            if (finalBrightness > 0.7 && star.size > 1) {
                const glowSize = star.size * 2;
                const glowGradient = ctx.createRadialGradient(
                    star.x, star.y, 0,
                    star.x, star.y, glowSize
                );
                glowGradient.addColorStop(0, `rgba(255, 255, 255, ${finalBrightness * 0.3})`);
                glowGradient.addColorStop(1, 'rgba(255, 255, 255, 0)');
                
                ctx.fillStyle = glowGradient;
                ctx.beginPath();
                ctx.arc(star.x, star.y, glowSize, 0, Math.PI * 2);
                ctx.fill();
            }
            
            // 绘制星星主体
            if (star.color === '#FFFFFF') {
                ctx.fillStyle = `rgba(255, 255, 255, ${finalBrightness})`;
            } else {
                // 有颜色的星星
                const rgb = star.color === '#FFE4B5' ? '255, 228, 181' : '230, 230, 250';
                ctx.fillStyle = `rgba(${rgb}, ${finalBrightness})`;
            }
            
            ctx.beginPath();
            ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
            ctx.fill();
            
            // 为最亮的星星添加十字光芒效果
            if (finalBrightness > 0.8 && star.size > 1.5) {
                ctx.strokeStyle = `rgba(255, 255, 255, ${finalBrightness * 0.6})`;
                ctx.lineWidth = 0.5;
                ctx.beginPath();
                // 垂直线
                ctx.moveTo(star.x, star.y - star.size * 3);
                ctx.lineTo(star.x, star.y + star.size * 3);
                // 水平线
                ctx.moveTo(star.x - star.size * 3, star.y);
                ctx.lineTo(star.x + star.size * 3, star.y);
                ctx.stroke();
            }
        });
    }
    
    update() {
        if (!this.isPaused) {
            this.time += this.speedMultiplier;
            
            // 更新行星角度
            this.planets.forEach(planet => {
                planet.angle += planet.speed * this.speedMultiplier;
                
                // 更新卫星角度
                if (planet.satellites) {
                    planet.satellites.forEach(satellite => {
                        satellite.angle += satellite.speed * this.speedMultiplier;
                    });
                }
            });
        }
    }
    
    draw() {
        const ctx = this.ctx;
        
        // 清空画布
        ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制星空背景
        this.drawStars();
        
        // 绘制太阳
        this.drawSun();
        
        // 绘制行星
        this.planets.forEach(planet => {
            this.drawPlanet(planet);
        });
        
        // 绘制信息
        this.drawInfo();
    }
    
    drawInfo() {
        const ctx = this.ctx;
        ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
        ctx.font = '12px Arial';
        ctx.textAlign = 'left';
        ctx.fillText(`速度: ${this.speedMultiplier.toFixed(1)}x`, 20, this.canvas.height - 40);
        ctx.fillText(`时间: ${Math.floor(this.time / 10)}`, 20, this.canvas.height - 20);
    }
    
    animate() {
        this.update();
        this.draw();
        this.animationId = requestAnimationFrame(() => this.animate());
    }
    
    start() {
        if (!this.animationId) {
            this.isPaused = false;
            this.animate();
        }
    }
    
    pause() {
        this.isPaused = true;
        if (this.animationId) {
            cancelAnimationFrame(this.animationId);
            this.animationId = null;
        }
    }
    
    reset() {
        this.time = 0;
        this.planets.forEach(planet => {
            planet.angle = 0;
            planet.trail = [];
            
            // 重置卫星
            if (planet.satellites) {
                planet.satellites.forEach(satellite => {
                    satellite.angle = 0;
                    satellite.trail = [];
                });
            }
        });
        this.speedMultiplier = 1;
        document.getElementById('speed').value = 1;
        document.getElementById('speedValue').textContent = '1.0x';
        
        if (this.isPaused) {
            document.getElementById('pauseBtn').textContent = '暂停';
            this.isPaused = false;
            this.start();
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new SolarSystem();
}); 